<?php

namespace app\saas\service;

use app\common\model\trAdmin;
use app\common\model\trAdminSession;
use app\common\util\TcScfUtil;
use app\saas\model\trMall;
use app\common\model\trResource;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use app\saas\model\trSetting;

/**
 * Class Auth
 * @package app\admin\service
 * 登录服务类
 */
class LoginService
{
    private $params;
    private $returnData;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
    }

    // 账号密码登录
    public function LoginByAccount(){
        if (empty($this->params["account"])) {
            return ErrorCode::code("params_not_exist", "账户名");
        }
        if (empty($this->params["password"])) {
            return ErrorCode::code("params_not_exist", "密码");
        }
        $data = trAdmin::getAdminInfo($this->params['account'], "id,username,type,status,expired_time,password,salt");
        if (!empty($data)) {
            if($data['password'] != generate_password($this->params['password'], $data["salt"])) {
                return ErrorCode::code("account_error");
            }
            if($data["type"] != "1" && !empty($data["expiredTime"]) && $data["expiredTime"] <= time()){
                return ErrorCode::code('account_expired');
            }
            if($data["status"] == "3"){
                return ErrorCode::code('customized', "账号已被删除，请联系管理员");
            }elseif($data["status"] == "2"){
                $this->returnData = ErrorCode::code('account_disable');
            }else {
                $sessionId = trAdmin::generateSessionId();
                $data["loginIp"] = Tools::get_client_ip();
                $data["isSaas"] = "1"; // saas端已登陆
                $data["tokenTime"] = time() + config("session_expire");
                //保存token
                $result = trAdminSession::add([
                    "admin_id" => $data['id'], "session_id" => $sessionId, "login_ip" => $data["loginIp"], "create_time" => time(),
                    "expire_time" => $data["tokenTime"], "is_saas" => $data["isSaas"]
                ]);
                if (isset($result['code'])) {
                    return $result;
                }
                unset($data["password"], $data["salt"]);
                cache("SaaS_" . $sessionId, $data, config("session_expire")); //缓存用户信息
                $this->returnData['data'] = ['token' => $sessionId];
            }
        } else {
            $this->returnData = ErrorCode::code("account_not_exist");
        }
        return $this->returnData;
    }

    /**
     * @param $sessionId
     * @return bool|mixed
     * 判断sessionID是否有效
     */
    public static function checkSession($sessionId){
        if (!$adminData = cache("SaaS_" . $sessionId)) {
            if (empty($data = trAdminSession::getFields("expire_time,admin_id,login_ip,is_admin,is_saas", ["session_id" => $sessionId], true, false))) {
                return false;
            }
            if (time() > $data["expireTime"]) { //sessionId过期了
                return false;
            }
            if($data["isSaas"] == "3"){ // 已退出了
                if($data["isAdmin"] == "1"){ // 还登录着
                    trAdminSession::doUpdate(["is_saas" => "1"], ["session_id" => $sessionId]);
                }else {
                    return false;
                }
            }
            if (!empty($adminData = trAdmin::getAdminInfo($data['adminId'], "id,username,type,status,expired_time"))) {
                $adminData["loginIp"] = $data["loginIp"];
                $adminData["isSaas"] = "1";
                $adminData["tokenTime"] = $data["expireTime"];
                if($data["isSaas"] == "0"){ // 未登陆，改成登陆
                    trAdminSession::doUpdate(["is_saas" => "1"], ["session_id" => $sessionId]);
                }
                cache("SaaS_" . $sessionId, $adminData, $data["expireTime"] - time());
            } else {
                return false;
            }
        }else{
            if($adminData["isSaas"] == "3"){ // 退出了
                return false;
            }
            if($adminData["isSaas"] == "0"){ // SaaS未登陆
                trAdminSession::doUpdate(["is_saas" => "1"], ["session_id" => $sessionId]);
                $adminData["isSaas"] = "1";
                cache("SaaS_" . $sessionId, $adminData, $adminData["tokenTime"] - time());
            }
        }
        if($adminData["type"] != "1"){ // 不是超管，要判断账号是否到期等等
            if($adminData["status"] == "2"){
                return ErrorCode::code('account_disable');
            }
            if($adminData["status"] == "3"){
                return ErrorCode::code('customized', "账号已被删除，请联系管理员");
            }
            if(!empty($adminData["expiredTime"]) && $adminData["expiredTime"] <= time()){
                return ErrorCode::code('account_expired');
            }
        }
//        if(isset($data["loginIp"]) && ($data["loginIp"] != Tools::get_client_ip())){
//            $this->returnData =   ErrorCode::code("ip_token_error");
//            return false;
//        }
        return $adminData;
    }

    //清除登录token
    public function clearSession($id, $sessionId){
        if(empty($id) && empty($sessionId)){
            return true;
        }
        trAdminSession::doUpdate(["is_saas" => "3"], ["admin_id" => $id, "session_id" => $sessionId]);
        if (!$adminData = cache("admin_" . $sessionId)) {
            cache("admin_" . $this->params['token'], null);
        }
        return true;
    }

    //登录者信息
    public function getLoginInfo($admin_id){
        $data = trAdmin::getAdminInfo($admin_id);
        if($data){
            if(empty($data["expiredTime"])){
                $data["expiredTime"] = "永久";
            }else{
                $data["expiredTime"] = date("Y-m-d", $data["expiredTime"]);
            }
            $data["isSuper"] = $data["type"] == '1' ? true : false; // 1 - 超级管理员 | 其它 - 普通管理员
            $data['avatar'] = tome_dia(!empty($data['avatar']) ? trResource::getValue("url", ["id" => $data["avatar"]]) : "/attachment/default/n1wAgn1jD8GnNQ1LnWd8j1W8898nGL.png");
            unset($data['password'], $data['salt']);
            $data["createCount"] = trMall::getCount(["manager_id" => $data["id"]]);
            if(!is_numeric($data["appCount"])){
                $data["canCreate"] = "无限制";
            }else{
                $data["canCreate"] = $data["appCount"] - $data["createCount"];
            }
            $tcConfig = trSetting::getFields("secret_id,secret_key");
            if(!empty($tcConfig["secretId"]) && !empty($tcConfig["secretKey"])){
                $scf = new TcScfUtil($tcConfig["secretId"], $tcConfig["secretKey"]);
                $res = $scf->describeAccountBalance(); // 余额
                if($res["code"] == "0"){
                    $data["tcAccountInfo"] = ["balance" => $res["data"]["Balance"] / 100, "result" => "获取成功"];
                }else{
                    $data["tcAccountInfo"] = ["balance" => 0, "result" => $res["msg"]];
                }
            }else{
                $data["tcAccountInfo"] = ["balance" => 0, "result" => "未配置腾讯云信息"];
            }
        }
        $this->returnData['data'] = $data;
        return $this->returnData;
    }

    //退出登陆
    public function logout($admin_id)
    {
        $this->clearSession($admin_id, $this->params['token']);
        return $this->returnData;
    }

    // 登录页的配置
    public function getConfig()
    {
        $settingData = trSetting::getFields("logo,site_title,seo_title,copyright");
        if(empty($settingData)){
            foreach (explode(",", "logo,site_title,seo_title,copyright") as $field){
                $settingData[parse_name($field)] = null;
            }
        }else{
            $settingData["logo"] = tome_dia(trResource::getValue("url", ["id" => $settingData["logo"]]));
        }
        $this->returnData['data'] = $settingData;
        return $this->returnData;
    }
}